<template>
	<view>
		<view class="pl25 pr25" v-if="isUserId">
			<view class="pl20 pr20 bb box flex flex-ac" style="margin-bottom: 30rpx;margin-top: 50rpx;">
				<view class="it1 flex flex-ac">
					<text style="font-size: 30rpx;">找不到消息记录？绑定手机号试试</text>
					<button class='login_btn' style="line-height: 1.5;padding-left: 1;background-color: #F73809;font-size: 30rpx;margin-right: 1rpx;" type='primary' open-type="getPhoneNumber"  @getphonenumber="getPhoneNumber">
					  登录
					</button>
				</view>
			</view>
		</view>
		<view class="title ft12 c999" id="sticky-nav">您有{{messReadNum}}条未读消息</view>
		<view class="pl25 pr25" style="padding-left: 0rpx;padding-right: 0rpx;border-top: 2rpx solid #DBDBDB;">
			<view v-for="(item,index) in arr" :key="item.id" class="msg_card"  @click="navigateToChat(item)" style="position: relative;">
				<image class="head" :src="item.orderId.indexOf('follow')>-1?'../../static/images/sfb@2x.png':item.doctorHead?item.doctorHead:avatarUrl" style="height: 120rpx;width: 120rpx;margin-right: 20rpx;border-radius: 50%;" mode="heightFix"></image>
				<view style="height: 60%;width: calc( 100% - 140rpx);display: flex;flex-direction: column;justify-content: space-between;">
					<view style="display: flex;align-items: center;justify-content: space-between;">
						<view style="font-weight: bolder;font-size: 32rpx;">{{item.doctorNickname}}</view>
						<view style="color: #BBBBBB;">{{changeDateFormat(item.adddate)}}</view>
					</view>
					<view style="font-size: 28rpx;color: #BBBBBB;width: 100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
						{{item.content?item.content:'--'}}
					</view>
					<!-- <text class="abs noread" v-if="item.readed == 0"></text> -->
				</view>
				<view v-if="item.readed == 0" style="position: absolute;top: 20rpx;left: 120rpx;width: 20rpx;height: 20rpx;border-radius: 50%;background-color: #F73809;"></view>
			</view>
			
		</view>
		<uni-load-more :status="message" :contentText="contentText" @clickLoadMore="loadMore"></uni-load-more>
		<uni-popup ref="popup" type="message">
		    <uni-popup-message :type="warnType" :message=warnMessage :duration="warnTime"></uni-popup-message>
		</uni-popup>
		
		<view style="position: fixed;bottom: 200rpx;right: 50rpx;
			width: 120rpx;height: 120rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			z-index: 999;"
			@click="reloadCharList">
			<image src="../../static/images/daochu.png" style="width: 100%;" mode="widthFix"></image>
		</view>
		<CustomTabBar current="/pages/mess/index" />
	</view>
</template>

<script>
	import CustomTabBar  from '@/components/CustomTabBar/index.vue';
	let disp = require("../../utils/broadcast");
	const WxAuth =  require('@/utils/wxlogin');
	export default {
		components: {
			CustomTabBar
		},
		data() {
			return {
				avatarUrl:'http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/user.png',//微信头像
				warnMessage:'错误',//消息内容
				warnType:'warn',//消息类型  success/warn/info/error
				warnTime:1000,//消息提醒延长时间
				isUserId:false,
				hasNextPage: true, //是否有下一页
				message: 'noMore',
				contentText: {
					contentdown: "点击显示更多",
					contentrefresh: "正在加载...",
					contentnomore: "没有更多数据了"
				},
				// noReadNum:0,//未读消息数量
				pageIndex:0,//获取聊天记录上一页
				orderArray:[],//聊天记录
				arr: [],
				unReadSpotNum: 0,
				pageIndex: 1,
				userId:'',//用户id
				messReadNum: 0,
				isclickIng: false,
				hasNextPage: true,
				passopenid:'',
			};
		},
		onLoad(option) {
			WxAuth.onLogin();
			disp.on("noReadNumChatListNumber",(c)=>{
				this.getCharList(this.userId,this.pageIndex);//获取会话列表
				this.messReadNum = c
			});
			//微信分享
			wx.showShareMenu({
			      withShareTicket: true,
			      menus: ['shareAppMessage', 'shareTimeline']
			    });  
		},
		//分享
		onShareTimeline: function (res) {
				var that = this;
				return {
					title: `邛崃民众门诊部`,
					imageUrl: `../../static/images/yymc.png`,
					query: "",
					success: function (res) { },
				};
		},
		onShareAppMessage: function (res) {
				return {
					title: `邛崃民众门诊部`,
					imageUrl: `../../static/images/yymc.png`,
					path: "/pages/xxxx/xxx" ,
					success: function (res) { },
				};
		},
		onShow() {
			this.getopenId()
			var that = this;
			var userId = uni.getStorageSync("usrUserId");
			if(userId){
				this.isUserId = false;
				that.userId = userId;
				var content = that.pageIndex;
				this.getCharList(userId,content);//获取会话列表
				this.selectChatListNumber(userId)
			}else{
				// this.isUserId = true;
				// uni.reLaunch({
				// 	url: '/pages/index/index'
				// })
			}
		},
		methods: {
			//强行
			getopenId(){
				var usrUserId=uni.getStorageSync('usrUserId')
				var code=uni.getStorageSync('code')
				var openId=uni.getStorageSync('openId')
				if(usrUserId&&(!openId || openId=='')){
						uni.request({
							url: 'https://app.mzmzb.com/application-usrapp/wx/getOpenIdByHspId.tz',
							method: 'get',
							data: {
								code: code,
								userId: usrUserId,
								hspId: this.hspId
							},
							success: (res) => {
								uni.setStorageSync('openId',res.data.errMsg)
							}
						})
				}
			},
			// getReadNum(){
			// 	return this.noReadNum.toString()
			// },
			reloadCharList(){
				var that = this;
				var userId = uni.getStorageSync("usrUserId");
				if(userId){
					this.isUserId = false;
					that.userId = userId;
					var content = that.pageIndex;
					this.getCharList(userId,content);//获取会话列表
				}else{
					this.isUserId = true;
				}
			},
			//登录
			getPhoneNumber:function(e){
				var that = this;
				if(e.detail.errMsg.indexOf('fail')==-1){
					that.encryptedData = e.detail.encryptedData;
					that.iv = e.detail.iv;
					that.getCode(e.detail.encryptedData,e.detail.iv,this.hspId);
				}
			},
			//获取用户id并存入缓存
			getCode(encryptedData,iv,hspId){
				var that = this;
				 WxAuth.checkSession().then(code => {
					  WxAuth.getUserIdByPhone(code,encryptedData,iv,hspId).then(res =>{
						  if(res.success){
								that.warnMessage = '登录成功';
								that.warnType = 'success';
								that.$refs.popup.open();
								that.loginHX(res.result);//登录环信
								that.isUserId = false;
								that.userId = res.result;
								//初始化数据关注医生数量
								that.getCharList(res.result, that.pageIndex)
							}else{
								that.warnMessage = res.errMsg;
								that.warnTime = 2000;
								that.$refs.popup.open();
							}
							
						  })
				 })
			},
			gethx(userId){
				let openid=uni.getStorageSync('openId')
				setTimeout(()=>{
					this.func.$requset('login/hxLogin.tz',{usrUserId:userId},'POST').then(item=>{
						var test_account = userId + '';
						uni.setStorageSync("test_psword", item.data.errMsg)
					})
				},2000)
				
			},
			//登录环信
			loginHX(userId){
						var test_account = userId+'';
						let test_psword=''
						if(uni.getStorageSync("test_psword")){
							test_psword = uni.getStorageSync("test_psword")
						}else{
							this.gethx(userId)
							test_psword = uni.getStorageSync("test_psword")
						}
						uni.setStorageSync("usrUserId",test_account)
						uni.setStorageSync("myUsername",test_account);
						this.$conn.open({
							apiUrl: this.$im.config.apiURL,
							user: test_account,
							pwd: test_psword,
							grant_type: "password",
							appKey: this.$im.config.appkey
						});
			
			},
			//加载更多
			loadMore(e) {
				if (e.detail.status == 'more') {
					var that = this;
					that.message = 'loading';
					that.pageIndex = that.pageIndex + 1;
					setTimeout(() => {
						that.getCharList(that.userId, that.pageIndex)
						if (that.hasNextPage) {
							that.message = 'more';
						} else {
							that.message = 'noMore';
						}
					}, 500);
				}
			},
			selectChatListNumber(userId,orderId,orderExt){
				let that = this;
				this.func.$request('wx/selectChatListNumber.tz',{receive : userId},'GET').then(res=>{
					if(res.data.success){
						let count = res.data.result;
						this.messReadNum = count
						if(count>0){
							uni.setTabBarBadge({
								index: 1,
								text: count.toString()
							})
						}else{
							uni.removeTabBarBadge({
									index: 1
							})
						}
						if(orderId&&orderExt){
							that.tochartpage(orderId,orderExt)
						}
					}
				})
			},
			getCharList(userId,content){
				var that = this;
				that.loginHX(userId)
				let openid=uni.getStorageSync('openId')
				this.func.$request('wx/selectChatList.tz',{receive : userId,content:content},'GET').then(res=>{
					if(res.data.success){
						that.hasNextPage = res.data.result.hasNextPage;
						if (that.hasNextPage) {
							that.message = 'more';
						} else {
							that.message = 'noMore';
						}
						that.arr = res.data.result;
						// if(that.arr.length>0){
						// 	var count = 0;
						// 	that.arr.forEach(function(item,index){
						// 		if(item.readed ==0 ){	
						// 			if(item.messageType == '图文订单'||item.messageType == '视频订单'){
						// 				count++;
						// 			}
						// 		}
						// 	});
						// 	that.noReadNum = count;
						// }
						console.log('getCharList',that.arr)
					}else {
						that.message = 'noMore';
					}
					
				}).catch(error=>{
						that.message = 'noMore';
				})
			},
			navigateToChat(item){
				if (!item.orderId || this.isclickIng) {
					return;
				}
				this.isclickIng = true
				if(item.orderId.indexOf('follow')>-1){
					let orderId = item.orderId
					let followId = orderId.substring(orderId.indexOf('_')+1)
					this.isclickIng = false
					uni.navigateTo({
					    url: '/pages3/suifangxq/index?followId='+followId+'&orderId='+item.orderId+'&readed='+item.readed
					});
				}else{
					if (!item.orderId || !item.doctorId || !item.doctorHead || !item.doctorNickname || !item.userId || !item.userHead || !item.userNickname) {
						this.isclickIng = false
						return;
					}
					var that = this;
					var orderExt = {};//发消息所需要的拓展数据
					orderExt.orderId = item.orderId;
					orderExt.messageType = item.messageType;
					orderExt.doctorId = item.doctorId;
					orderExt.doctorHead = item.doctorHead;
					orderExt.doctorNickname = item.doctorNickname;
					orderExt.userId = item.userId;
					orderExt.userHead = item.userHead;
					orderExt.userNickname = item.userNickname;
					//设置已读状态
					that.settingRead(item.orderId,item.readed,JSON.stringify(orderExt));
					// 查询订单是否已经结束
				}
			},
			//格式化时间
			changeDateFormat(cellval) {
			　　　　var dateVal = cellval + "";
			　　　　if (cellval != null) {
			　　　　　　var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
			　　　　　　var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
			　　　　　　var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
			　　　　　　var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
			　　　　　　var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
			　　　　　　var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			            return	month + "月" + currentDate + "日"+ " " + hours + ":" + minutes
			　　　　　　//return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
			　　　　}
			
			　},
			//设置已读状态
			settingRead(orderId,readed,orderExt){
				var that = this;
				// if(readed == 0){
					var that = this;
					that.func.$request('wx/settingRead.tz',{orderId : orderId},'GET').then(res=>{
						that.isclickIng = false
						if(res.data.success){
							// if(that.noReadNum>0){
							// 	that.noReadNum--
							// 	if(that.noReadNum>0){
							// 		uni.setTabBarBadge({
							// 			index: 1,
							// 			text: that.noReadNum.toString()
							// 		})
							// 	}else{
							// 		uni.setTabBarBadge({
							// 			index: 1
							// 		})
							// 	}
								
							// 	
							// }
							let userId = uni.getStorageSync("usrUserId");
							that.selectChatListNumber(userId,orderId,orderExt)
						}
					}).catch(error=>{
						that.isclickIng = false
					})
			},
			tochartpage(orderId,orderExt){
				this.func.$request('wx/getOrderInfo.tz',{orderId : orderId},'GET').then(res=>{
					let extObj = JSON.parse(orderExt)
					extObj.ordStatus = res.data.result
					uni.navigateTo({
						url: '/pages/chatroom/chatroom?username=' + JSON.stringify(extObj)
					});
				})
			}
        }
	};
</script>

<style lang="less">
	.msg_card{
		height: 150rpx;
		border-bottom: 2rpx solid #DBDBDB;
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-left: 26rpx;
		padding-right: 26rpx;
		box-sizing: border-box;
	}
	page{
		background: #efefef;
	}
	#sticky-nav {
		position: -webkit-sticky;
		position: sticky;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 10;
		background: #fff;
	}
	.title{
		height: 90rpx;
		line-height: 90rpx;
		padding-left: 55rpx;
	}
	.noread{
		width: 24rpx;
		height: 24rpx;
		background: #fec322;
		border-radius: 50%;
		right: 0;
		top: 0;
		z-index:5;
	}
</style>
